package com.dongdong.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.dongdong.mapper.TbItemCatMapper;
import com.dongdong.model.TbItemCat;
import com.dongdong.model.TbItemCatExample;
import com.dongdong.service.SpecificationOptionService;
import com.dongdong.service.TbItemCatService;
import com.dongdong.service.TypeTemplateService;
import com.dongdong.vo.SpecificationOptionVO;
import com.dongdong.vo.SpecificationVO;
import com.dongdong.vo.TbItemCatVO;
import com.dongdong.vo.TypeTemplateVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TbItemCatServiceImpl implements TbItemCatService {

    @Autowired
    private TbItemCatMapper tbItemCatMapper;

    @Autowired
    private TypeTemplateService typeTemplateService;

    @Autowired
    private SpecificationOptionService specOptionService;

    @Override
    public List<TbItemCatVO> getItemCat(Long pid) {
        TbItemCatExample example = new TbItemCatExample();
        example.createCriteria().andParentIdEqualTo(pid);
        List<TbItemCat> tbItemCats = tbItemCatMapper.selectByExample(example);
        //转转
        List<TbItemCatVO> vos = tbItemCats.stream().map((tbItemCat) ->{
            TbItemCatVO vo = new TbItemCatVO();
            BeanUtils.copyProperties(tbItemCat, vo);
            return vo;
        }).collect (Collectors.toList());
        return vos;
    }

    @Override
    public TypeTemplateVO getTypetemplate(Long id) {
        // 根据id查询分类对象
        TbItemCat tbItemCat = tbItemCatMapper.selectByPrimaryKey(id);
        //根据分类中的模板id去模板表中查询模板信息
        TypeTemplateVO typeTemplateVO = typeTemplateService.selectTypeTemplateById(tbItemCat.getTypeId());


        //封装规格和规格组成数据
        String specIds = typeTemplateVO.getSpecIds();
        //[{"id":27,"text":"网络"},{"id":32,"text":"机身内存"}]
        List<SpecificationVO> specVOS = JSONObject.parseArray(specIds, SpecificationVO.class);

    //查询所有的规格组成数据
    List<SpecificationOptionVO>  optionVOS = specOptionService.findAllOption();
    Map<Long, List<SpecificationOptionVO>> map = optionVOS.stream().collect(Collectors.groupingBy((x) -> {
        return x.getSpecId();
    }));
    for (SpecificationVO specVO : specVOS) {
        Long key = specVO.getId();
        List<SpecificationOptionVO> specOptionVOS = map.get(key);
        specVO.setOptionVOS(specOptionVOS);
    }
        typeTemplateVO.setSpecificationVOS (specVOS);


        return typeTemplateVO;

    }























}
